package controllers

import (
	// "bytes"
	"crypto/md5"
	"encoding/json"
	"fmt"
	model "mars-backend/models"
	// "io"
	"net/http"
	// "time"
	// "strconv"

	"mars-backend/utils"

	"github.com/astaxie/beego"
	"gopkg.in/mgo.v2/bson"
)

type LoginController struct {
	beego.Controller
}

const (
	//UserTable 评论表(准确的说是db的collection)
	UserTable = "users"
)

var SavedCookies = make(map[string]string)

//用户登录
func (uct *LoginController) Login() {
		body := uct.Ctx.Input.RequestBody
	var paras map[string]string
	err := json.Unmarshal(body, &paras)
	uct.HandleError(err)

	mobile := paras["mobile"]
	password := paras["password"]

	data := []byte(password)
	has := md5.Sum(data)
	passwordmd5 := fmt.Sprintf("%x", has)
	beego.Info("passwordmd5")
	beego.Info(passwordmd5)

	session, err := utils.GetMongoSession()
	uct.HandleError(err)
	defer session.Close()

	utable := session.DB("").C(UserTable)

	var result model.User

	utable.Find(bson.M{"mobile": mobile, "isdelete": 0}).One(&result)
	beego.Info("error")
	beego.Info(result.ID == "")
	if result.ID == "" {
		uct.HandleError(fmt.Errorf("请先注册，再登录"))
	}

	if result.Password != passwordmd5 {
		uct.HandleError(fmt.Errorf("密码错误"))
	}

	// id := result.ID

	resMap := make(map[string]interface{})
	resMap["user"] = result
	resData, err := json.Marshal(resMap)
	uct.HandleError(err)

	uct.Ctx.Output.Status = http.StatusOK
	uct.Ctx.Output.Body(resData)
}

// 取消删除用户

// 查询图表结果

// 

//HandleError 错误处理函数
func (uct *LoginController) HandleError(err error) {

	if err != nil {
		fmt.Println(err.Error())
		uct.Ctx.Output.Status = http.StatusServiceUnavailable
		uct.Ctx.Output.Body([]byte(err.Error()))
		uct.StopRun()
	}

}
